<template>
  <view v-if="visible" class="add-friend-modal" >
    <!-- 遮罩层 -->
    <view 
      class="modal-mask" 
      :class="{ 'modal-mask-visible': visible }"
      @tap="handleMaskClick"
    ></view>

    <!-- 弹窗内容：使用动态 bottom 避开键盘 -->
    <view 

      class="modal-content" 
      :class="{ 'modal-content-visible': visible }"
      :style="{ paddingBottom: keyboardHeight + 'px' }"
    >
      <view class="modal-header">
        <text class="modal-title">添加好友</text>
        <view class="modal-close" @tap="handleClose">
          <text class="modal-close-icon">✕</text>
        </view>
      </view>

      <view class="modal-form"  >
        <view class="form-item">
          <view class="form-label">姓名</view>
          <view class="form-input">
            <input 
              type="text" 
              placeholder="请输入好友姓名" 
			  placeholder-style="color:#dedede"
              v-model="form.remarkName"
		      auto-focus
			  	@blur="onInputBlur"
              @input="handleInput('name')"
                />
          </view>
          <view class="form-error" v-if="errors.remarkName">
            <text>{{ errors.remarkName }}</text>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">手机号码</view>
          <view class="form-input">
            <input 
			type="tel" 
			@blur="onInputBlur"
			 placeholder-style="color:#dedede"
		    placeholder="请输入好友手机号码" 
            v-model="form.telePhone"
            @input="handleInput('phone')"
        
            />
          </view>
          <view class="form-error" v-if="errors.telePhone">
            <text>{{ errors.telePhone }}</text>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label">附言</view>
          <view class="form-input">
            <input 
              type="text" 
			   placeholder-style="color:#dedede"
              placeholder="请输入附言（可选）" 
		
              v-model="form.applyMsg"
           
            />
          </view>
        </view>

        <view class="form-submit" >
          <button @tap='handleSubmit'
            type="submit" 
            class="submit-btn"
            :disabled="isSubmitting||!form.remarkName||!form.telePhone"
          >
            <text v-if="!isSubmitting">确认添加</text>
            <text v-else>提交中...</text>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
const friendManger=uniCloud.importObject('friend',{customUI:true})
export default {
  name: 'AddFriendModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: { remarkName: '', telePhone: '', applyMsg: '' },
      errors: { remarkName: '', telePhone: '' },
      isSubmitting: false,
      isNameFocused: false,
      keyboardHeight: 0, // 当前键盘高度
      isKeyboardVisible: false,
	  currentFocus: ""
    };
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.resetForm();
        this.$nextTick(() => {
          setTimeout(() => {
            this.isNameFocused = true;
          }, 200);
        });
        this.startKeyboardListener();
      } else {
        this.stopKeyboardListener();
        this.isNameFocused = false;
        this.keyboardHeight = 0;
      }
    }
  },
  methods: {
    // 启动键盘监听
    startKeyboardListener() {
      // 微信小程序：通过 window.innerHeight 变化判断
      // H5/App：使用 keyboardheightchange 事件
      if (typeof uni.onKeyboardHeightChange === 'function') {
        // H5 / App 支持 onKeyboardHeightChange
        uni.onKeyboardHeightChange(this.handleKeyboardHeightChange);
      } else {
        // 微信小程序等：监听 resize（不完美但可用）
        this.resizeHandler = () => {
          const windowHeight = document.documentElement.clientHeight || window.innerHeight;
          const newHeight = window.innerHeight - windowHeight;
          if (newHeight > 100) {
            this.keyboardHeight = newHeight;
            this.isKeyboardVisible = true;
          } else {
            this.keyboardHeight = 0;
            this.isKeyboardVisible = false;
          }
        };
        window.addEventListener('resize', this.resizeHandler);
      }
    },

    // 停止监听
    stopKeyboardListener() {
      uni.offKeyboardHeightChange(this.handleKeyboardHeightChange);
      if (this.resizeHandler) {
        window.removeEventListener('resize', this.resizeHandler);
        this.resizeHandler = null;
      }
      this.keyboardHeight = 0;
    },

    // 处理键盘高度变化（H5 / App）
    handleKeyboardHeightChange(res) {
      if (res.height > 100) {
        this.keyboardHeight = res.height;
        this.isKeyboardVisible = true;
      } else {
        this.keyboardHeight = 0;
        this.isKeyboardVisible = false;
      }
    },

    // 输入框聚焦（可选：确保组件响应）
    onInputFocus() {
      // 可用于调试
    },
    onInputBlur() {
	uni.hideKeyboard()
      
    },

    handleClose() {
      this.$emit('close');
    },
    handleMaskClick() {
      this.handleClose();
    },
    handleInput(field) {
      this.errors[field] = '';
    },
    handleSubmit() {
		console.log('1111111111');
      if (!this.validateForm()) return;
      this.submitForm();
    },
    validateForm() {
      let isValid = true;
      const trimmedName = this.form.remarkName.trim();
      if (!trimmedName) {
        this.errors.name = '请输入好友姓名';
        isValid = false;
      } else if (trimmedName.length > 10) {
        this.errors.name = '姓名长度不能超过10个字符';
        isValid = false;
      }

      const trimmedPhone = this.form.telePhone.trim();
      if (!trimmedPhone) {
        this.errors.phone = '请输入好友手机号码';
        isValid = false;
      } else if (!/^1[3-9]\d{9}$/.test(trimmedPhone)) {
        this.errors.phone = '请输入有效的手机号码';
        isValid = false;
      }
      return isValid;
    },
   async submitForm() {
      this.isSubmitting = true;
	  const user=this.$store.state.msg?.user
	  if(!user){
		  uni.showToast({
		  	title:'请重新登陆',
			position:'center'
		  })
		  return
	  }
	  try{
	const  res=await  friendManger.addFriendByTelePhone({user,...this.form})
	    uni.showToast({
	    	title:res.message,
			position:'center',
			icon:res.success?'success':'fail',
			duration:3000,
	    })
		setTimeout(()=>{
		   this.$emit('close');
		},3000)
	  
	  }catch(e){
		  console.error(e);
	  }finally{
		 this.isSubmitting = false; 
	  }

   
    },
    resetForm() {
      this.form = { remarkName: '', telePhone: '', applyMsg: '' };
      this.errors = { name: '', phone: '' };
      this.isSubmitting = false;
    }
  },
  beforeDestroy() {
    this.stopKeyboardListener();
  }
};
</script>

<style lang="scss" scoped>
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 999;
}
.modal-mask-visible {
  opacity: 1;
}
/* 关键：不再用 transform，而是用 padding-bottom 动态撑开 */
.modal-content {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 25rpx;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
  transition: transform 0.5s ease;
  z-index: 1000;
  /* 初始位置 */
  transform: translateY(100%);
}

.modal-content-visible {
  transform: translateY(0);
}

/* 其余样式保持不变 */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 20rpx;
  border-bottom: 1px solid #f0f0f0;
}
.modal-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}
.modal-close {
  width: 32px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.modal-close-icon {
  font-size: 20px;
  color: #999;
}
.modal-form {
  padding: 20px;
}
.form-item {
  margin-bottom: 16px;
}
.form-label {
  display: block;
  padding-left: 25rpx;
  font-size: 14px;
  font-weight: 600;
  color: #55aaff;
  margin-bottom: 8px;
}
.form-input input {
  width: 100%;
  height: 44px;
  padding: 0 12px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  box-sizing: border-box;
 
}
.form-error {
  margin-top: 4px;
  font-size: 12px;
  color: #ff4d4f;
}
.form-submit {
  margin-top: 24px;
}
.submit-btn {
  width: 100%;
  height: 48px;
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
}
.submit-btn[disabled] {
  background-color: #c0c4cc;
}
</style>